/* $Id: util.c,v 1.1 2006/03/19 20:13:52 jfb Exp $ */
/*
 * Copyright (c) 2004 Jean-Francois Brousseau <jfb@fugusec.net>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
 * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/types.h>

#include <string.h>
#include <stdlib.h>

static const struct mp_env {
	const char vname[32];
	const char vval[32];
} mod_perl_env[] = {
	{ "NEMOD_MOD_PERL", "1" },
};

#define MOD_PERL_NBENV   (sizeof(mod_perl_env)/sizeof(mod_perl_env[0]))




/*
* mod_perl_copyenv()
*
* Create a copy of the environment of the process in which we're executing
* and add mod_perl-specific variables.
* Returns a pointer to the newly allocated environment array, or NULL on
* failure.
*/

char**
perlmod_initenv(void)
{
	u_int i, envc;
	char **env_copy, *envp, tmp[128];

	/* first, figure out how large the original env is */
	for (envc = 0;; envc++) {
		if (nemod_env[i] == NULL)
			break;
	}

	env_copy = (char **)calloc(envc + MOD_PERL_NBENV + 1, sizeof(char *));
	if (env_copy == NULL) {
		mod_log(NLOG_ERR, "failed to copy environment: %s",
		    strerror(errno));
		return (NULL);
	}

	for (i = 0; i < envc; i++) {
#if 0
		env_copy[i] = strdup(nemod_env[i]);
		if (env_copy[i] == NULL) {
			mod_log(NLOG_ERR,
			    "failed to copy environment variable: %m");
			return (NULL);
		}
#endif
	}

	for (i = 0; i < MOD_PERL_NBENV; i++) {
		snprintf(tmp, sizeof(tmp), "%s=%s", mod_perl_env[i].vname,
		    mod_perl_env[i].vval);
		env_copy[envc + i] = strdup(tmp);
		if (env_copy[envc + i] == NULL) {
			return (NULL);
		}
	}

	env_copy[envc + MOD_PERL_NBENV] = NULL;

	return (env_copy);
}
